//
//  ViewController.m
//  ReplaceImagesInAssets
//
//  Created by liboxiang on 2019/4/12.
//  Copyright © 2019 liboxiang. All rights reserved.
//

#import "ViewController.h"
#import "ImageCell.h"
#import "ImageModel.h"
#import "ScriptHelper.h"

#define PathSeperator  @"#&#"           //图片路径分隔符
#define ImagesOldTxtName  @"ImagesOldTxtName.txt"           //存储旧图片的plist文件的名称
#define ImagesNewTxtName  @"ImagesNewTxtName.txt"           //存储新图片的plist文件的名称

@interface ViewController ()<NSTableViewDataSource,NSTableViewDelegate>
@property (weak) IBOutlet NSPathControl *pathControlOld;
@property (weak) IBOutlet NSPathControl *pathControlNew;

@property (weak) IBOutlet NSTableView *tableview;
@property (weak) IBOutlet NSTableView *bottomOldTableView;
@property (weak) IBOutlet NSTableView *bottomNewTableView;
@property (weak) IBOutlet NSButton *ifRemoveNewImageAffterExchange;

@property (nonatomic, strong) NSMutableArray *sameNamelist;
@property (nonatomic, strong) NSMutableArray *notSameNameOldlist;
@property (nonatomic, strong) NSMutableArray *notSameNameNewlist;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _sameNamelist = [NSMutableArray arrayWithCapacity:0];
    _notSameNameNewlist = [NSMutableArray arrayWithCapacity:0];
    _notSameNameOldlist = [NSMutableArray arrayWithCapacity:0];
    
    // Do any additional setup after loading the view.
    _tableview.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone;
    _bottomOldTableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone;
    _bottomNewTableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone;
    [_tableview setGridStyleMask:NSTableViewSolidHorizontalGridLineMask];
    [_bottomOldTableView setGridStyleMask:NSTableViewSolidHorizontalGridLineMask];
    [_bottomNewTableView setGridStyleMask:NSTableViewSolidHorizontalGridLineMask];
    
    [_tableview registerNib:[[NSNib alloc] initWithNibNamed:@"ImageCell" bundle:nil] forIdentifier:@"ImageCell"];
    [_bottomOldTableView registerNib:[[NSNib alloc] initWithNibNamed:@"ImageCell" bundle:nil] forIdentifier:@"ImageCell"];
    [_bottomNewTableView registerNib:[[NSNib alloc] initWithNibNamed:@"ImageCell" bundle:nil] forIdentifier:@"ImageCell"];
}

- (void)refreshList {
    [_sameNamelist removeAllObjects];
    [_notSameNameNewlist removeAllObjects];
    [_notSameNameOldlist removeAllObjects];
    
    [ScriptHelper runScript:@"CatAllFilePath" type:@"sh" launchPath:@"/bin/bash" arguments:@[_pathControlNew.URL.path,PathSeperator,[self filePathWithName:ImagesNewTxtName]]];
    [ScriptHelper runScript:@"CatAllFilePath" type:@"sh" launchPath:@"/bin/bash" arguments:@[_pathControlOld.URL.path,PathSeperator,[self filePathWithName:ImagesOldTxtName]]];
    
    //此处得到的路径数据中图片名都是没有@2x或@3x的，所以直接通过路径可能获取不到图片，该处的路径只是表示xxx文件夹下有xxx名称的图片，具体是几倍图要判断才能知道
    NSString *pathOld = [self filePathWithName:ImagesOldTxtName];
    NSString *imagesOldPaths = [NSString stringWithContentsOfFile:pathOld encoding:NSUTF8StringEncoding error:nil];
    NSArray *tmpStrArray = [imagesOldPaths componentsSeparatedByString:PathSeperator];
    NSMutableArray *mStrArray = [NSMutableArray arrayWithCapacity:0];
    for (NSString *str in tmpStrArray) {
        NSString *tmpStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([tmpStr containsString:@"ic_edit"]) {
            NSLog(@"%@ length = %ld",tmpStr,tmpStr.length);
        }
        [mStrArray addObject:tmpStr];
    }
    NSArray *pathsOld = [NSSet setWithArray:mStrArray].allObjects;
    
    NSString *pathNew = [self filePathWithName:ImagesNewTxtName];
    NSString *imagesNewPaths = [NSString stringWithContentsOfFile:pathNew encoding:NSUTF8StringEncoding error:nil];
    
    NSArray *tmpStrArray2 = [imagesNewPaths componentsSeparatedByString:PathSeperator];
    NSMutableArray *mStrArray2 = [NSMutableArray arrayWithCapacity:0];
    for (NSString *str in tmpStrArray2) {
        NSString *tmpStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [mStrArray2 addObject:tmpStr];
    }
    
    NSArray *pathsNew =  [NSSet setWithArray:mStrArray2].allObjects;
    
    NSMutableArray *sameNameListOld = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *sameNameListNew = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *notSameNameListOld = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *notSameNameListNew = [NSMutableArray arrayWithCapacity:0];
    if (pathsOld.count && pathsNew.count) {
        for (NSString *path in pathsOld) {
            NSString *name = [self imageNameFromPath:path];
            BOOL haveSameNameImage = NO;
            for (NSString *pathTmp in pathsNew) {
                NSString *nameTmp = [self imageNameFromPath:pathTmp];
                if ([name isEqualToString:nameTmp]) {
                    //有同名图片
                    [sameNameListOld addObject:path];
                    [sameNameListNew addObject:pathTmp];
                    haveSameNameImage = YES;
                    break;
                }
            }
            if (!haveSameNameImage) {
                [notSameNameListOld addObject:path];
            }
        }
        [notSameNameListNew addObjectsFromArray:pathsNew];
        [notSameNameListNew removeObjectsInArray:sameNameListNew];
        
        NSInteger count = sameNameListOld.count;
        NSMutableArray *arrayOld = [NSMutableArray arrayWithCapacity:count];
        NSMutableArray *arrayNew = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i < count; i++) {
            NSString *pathOld = sameNameListOld[i];
            NSString *pathNew = sameNameListNew[i];
            
            ImageModel *modelOld = [ImageModel new];
            modelOld.isSelected = NO;
            modelOld.showCheckBox = YES;
            modelOld.cellType = ImageCellTypeSameNameOld;
            modelOld.path = [pathOld stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            modelOld.name = [self imageNameFromPath:pathOld];
            [arrayOld addObject:modelOld];
            
            ImageModel *modelNew = [ImageModel new];
            modelNew.isSelected = NO;
            modelNew.showCheckBox = NO;
            modelNew.cellType = ImageCellTypeSameNameNew;
            modelNew.switchCheckBoxStatus = SwitchCheckBoxStatus1x | SwitchCheckBoxStatus2x | SwitchCheckBoxStatus3x;
            modelNew.path = [pathNew stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            modelNew.name = [self imageNameFromPath:pathNew];
            [arrayNew addObject:modelNew];
        }
        
        [self sortArray:arrayOld];
        [self sortArray:arrayNew];
       
        [_sameNamelist addObject:arrayOld];
        [_sameNamelist addObject:arrayNew];
        
        for (int i = 0; i < notSameNameListOld.count; i++) {
            NSString *pathOld = notSameNameListOld[i];
            ImageModel *modelOld = [ImageModel new];
            modelOld.isSelected = NO;
            modelOld.showCheckBox = YES;
            modelOld.cellType = ImageCellTypeNotSameNameOld;
            modelOld.path = [pathOld stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            modelOld.name = [self imageNameFromPath:pathOld];
            [_notSameNameOldlist addObject:modelOld];
        }
        
        for (int i = 0; i < notSameNameListNew.count; i++) {
            NSString *pathNew = notSameNameListNew[i];
            ImageModel *modelNew = [ImageModel new];
            modelNew.isSelected = NO;
            modelNew.showCheckBox = YES;
            modelNew.cellType = ImageCellTypeNotSameNameNew;
            modelNew.switchCheckBoxStatus = SwitchCheckBoxStatus1x | SwitchCheckBoxStatus2x | SwitchCheckBoxStatus3x;
            modelNew.path = [pathNew stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            modelNew.name = [self imageNameFromPath:pathNew];
            [_notSameNameNewlist addObject:modelNew];
        }
        
        //按名称排序
        [self sortArray:_notSameNameOldlist];
        //按名称排序
        [self sortArray:_notSameNameNewlist];
    }
    
    [_tableview reloadData];
    [_bottomOldTableView reloadData];
    [_bottomNewTableView reloadData];
}

- (void)sortArray:(NSMutableArray *)array {
    //按名称排序
    [array sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        ImageModel *model1 = (ImageModel *)obj1;
        ImageModel *model2 = (ImageModel *)obj2;
        return [model1.name compare:model2.name];
    }];
}

- (NSString *)imageNameFromPath:(NSString *)path {
    NSString *file = [path lastPathComponent];
    if (file.length) {
        NSString *name = [file stringByDeletingPathExtension];
        return name;
    }
    return @"";
}

- (NSString *)filePathWithName:(NSString *)fileName {
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *plistPath = [docPath stringByAppendingPathComponent:fileName];
    return plistPath;
}

- (IBAction)refreshListAction:(id)sender {
    if (_pathControlNew.stringValue.length && _pathControlOld.stringValue.length) {
        [self refreshList];
    }
}
- (IBAction)selectAllSameNameImage:(id)sender {
    NSArray *tmpArray = _sameNamelist[0];
    for (ImageModel *model in tmpArray) {
        model.isSelected = YES;
    }
    [_tableview reloadData];
}
- (IBAction)changeSameNameImage:(id)sender {
    NSArray *arrayOld = _sameNamelist[0];
    NSArray *arrayNew = _sameNamelist[1];
    NSInteger count = arrayOld.count;
    for (int i = 0; i < count; i++) {
        ImageModel *modelOld = arrayOld[i];
        ImageModel *modelNew = arrayNew[i];
        NSString *sss = @"";        //用来判断是否使用新图中的1倍、2倍、3倍图
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus1x) {
            sss = [sss stringByAppendingString:@"1"];
        }
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus2x) {
            sss = [sss stringByAppendingString:@"2"];
        }
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus3x) {
            sss = [sss stringByAppendingString:@"3"];
        }
        [ScriptHelper runScript:@"ExchangeImageInAssets" type:@"sh" launchPath:@"/bin/bash" arguments:@[modelOld.path,modelNew.path,sss,@"move_to"]];
    }
    _sameNamelist = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithCapacity:0],[NSMutableArray arrayWithCapacity:0], nil];
    [_tableview reloadData];
}
- (IBAction)moveSelectedImageOutSameNameList:(id)sender {
    //将同名列表中选中的项移出到非同名列表中
    NSMutableArray *tmpOldArray = _sameNamelist[0];
    NSMutableArray *tmpNewArray = _sameNamelist[1];
    
    NSMutableArray *tmpOld = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *tmpNew = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < tmpOldArray.count; i++) {
        ImageModel *modelOld = tmpOldArray[i];
        if (modelOld.isSelected) {
            modelOld.isSelected = NO;
            [tmpOld addObject:modelOld];
            ImageModel *model = tmpNewArray[i];
            model.showCheckBox = YES;
            [tmpNew addObject:model];
        }
    }
    
    [_notSameNameOldlist addObjectsFromArray:tmpOld];
    [_notSameNameNewlist addObjectsFromArray:tmpNew];
    
    [self sortArray:_notSameNameOldlist];
    [self sortArray:_notSameNameNewlist];
    
    [tmpOldArray removeObjectsInArray:tmpOld];
    [tmpNewArray removeObjectsInArray:tmpNew];
    [_tableview reloadData];
    [_bottomNewTableView reloadData];
    [_bottomOldTableView reloadData];
}
- (IBAction)changeImageInNotSameNameList:(id)sender {
    ImageModel *modelOld;
    ImageModel *modelNew;
    for (ImageModel *model in _notSameNameOldlist) {
        if (model.isSelected) {
            modelOld = model;
            break;
        }
    }
    for (ImageModel *model in _notSameNameNewlist) {
        if (model.isSelected) {
            modelNew = model;
            break;
        }
    }
    if (modelNew && modelOld) {
        NSString *sss = @"";        //用来判断是否使用新图中的1倍、2倍、3倍图
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus1x) {
            sss = [sss stringByAppendingString:@"1"];
        }
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus2x) {
            sss = [sss stringByAppendingString:@"2"];
        }
        if (modelNew.switchCheckBoxStatus & SwitchCheckBoxStatus3x) {
            sss = [sss stringByAppendingString:@"3"];
        }
        if (_ifRemoveNewImageAffterExchange.state == NSControlStateValueOn) {
            [ScriptHelper runScript:@"ExchangeImageInAssets" type:@"sh" launchPath:@"/bin/bash" arguments:@[modelOld.path,modelNew.path,sss,@"move_to"]];
            [_notSameNameNewlist removeObject:modelNew];
        }
        else {
            [ScriptHelper runScript:@"ExchangeImageInAssets" type:@"sh" launchPath:@"/bin/bash" arguments:@[modelOld.path,modelNew.path,sss,@"copy_to"]];
        }
        [_notSameNameOldlist removeObject:modelOld];
        [_bottomNewTableView reloadData];
        [_bottomOldTableView reloadData];
    }
}

#pragma mark NSTableViewDataSource

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    if (tableView == _tableview) {
        if (_sameNamelist.count) {
            NSArray *array = _sameNamelist[0];
            return array.count;
        }
    }
    if (tableView == _bottomOldTableView) {
        return _notSameNameOldlist.count;
    }
    if (tableView == _bottomNewTableView) {
        return _notSameNameNewlist.count;
    }
    return 0;
}

#pragma mark NSTableViewDelegate

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 100;
}

- (nullable NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row
{
    ImageCell *cellView = [tableView makeViewWithIdentifier:@"ImageCell" owner:self];
    ImageModel *model = nil;
    if (tableView == _tableview) {
        if ([tableColumn.identifier isEqualToString:@"old"]) {
            NSArray *array = (NSArray *)_sameNamelist[0];
            model = array[row];
        }
        else {
            NSArray *array = (NSArray *)_sameNamelist[1];
            model = array[row];
        }
    }
    else if (tableView == _bottomOldTableView) {
        model = _notSameNameOldlist[row];
    }
    else if (tableView == _bottomNewTableView) {
        model = _notSameNameNewlist[row];
    }
    if (model) {
        __weak typeof(self) weakSelf = self;
        [cellView refreshWithModel:model stateChange:^(ImageModel * _Nonnull model) {
            BOOL isSelected = model.isSelected;
            switch (model.cellType) {
                case ImageCellTypeSameNameOld:
                case ImageCellTypeSameNameNew:
                    model.isSelected = isSelected;
                    break;
                    
                case ImageCellTypeNotSameNameOld:
                    for (ImageModel *tmpModel in weakSelf.notSameNameOldlist) {
                        tmpModel.isSelected = NO;
                    }
                    model.isSelected = isSelected;
                    [weakSelf.bottomOldTableView reloadData];
                    break;
                case ImageCellTypeNotSameNameNew:
                    for (ImageModel *tmpModel in weakSelf.notSameNameNewlist) {
                        tmpModel.isSelected = NO;
                    }
                    model.isSelected = isSelected;
                    [weakSelf.bottomNewTableView reloadData];
                    break;
            }
        }];
    }
    return cellView;
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end
